from flask import Blueprint,request,jsonify,make_response
from  flask import  current_app as app
import json
import os
import uuid
from utils.mylist import myfile
from utils.db import  db
from utils.comm import xtree
from utils.myes import Es
from utils.comm import  get_data
from utils.jwts import myjwt
from utils.myacl import acl
from utils.myrbac import rbac
from utils.redisconn import  r

bp_user = Blueprint('users',__name__)


#用户登录
@bp_user.route('/login/',methods=['POST'])
def login():
    data = get_data()
    sql = "select * from users where mobile='%s'"%(data['mobile'])
    res = db.find_one(sql)
    #判断用户是否存在
    if res:
        if res['password'] == data['password']:
            #生成token
            data = {'data':{'mobile':res['mobile'],'userid':res['id'],'name':res['name']}}
            token = myjwt.jwt_encode(data)
            #用户权限 该用户权限集 这边只获取前端权限
            resall = acl.get_page_resource(res['id'])

            #获取前端用户的角色和资源
            get_jue_res = rbac.get_page_jue_resource(res['id'])
            resall.extend(get_jue_res)    

            #获取后端权限
            reshouall = acl.get_interface_resource(res['id'])
            #把后端所有权限存入redis
            key = 'interface'+str(res['id'])
            r.set_add(key,reshouall)



            return jsonify({"code":200,'mes':'登录成功','userid':res['id'],'name':res['name'],'mobile':res['mobile'],'token':token,'pagelist':resall})
        else:
            return jsonify({"code":20030,'mes':'用户名或密码有误'})
    else:
        return jsonify({"code":20020,'mes':'该用户不从在'})


#构建简单的2层分类
def gettwocate(data):
    lst = []
    idlist = []
    #把顶级id方在lst里
    for i in data:
        id = i['pid']
        #去掉重复的父id  列入 有4个 5 5 9 15  只剩下5 9 15 就是顶级父类
        if id not in idlist:
            lst.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    #循环添加数据的列表 需要下表
    for i,value in enumerate(lst):
        for j in data:
            # print(j)
            if value['id'] == j['pid']:
                lst[i]['son'].append({'id':j['id'],'name':j['name'],'url':j['url']})

    return  lst




#用户资源
@bp_user.route('/usermanage/')
async def usermanage():
    uid  = request.args.get('uid')
    # print(uid)
    #根据用户id查看用户有哪些权限
    # sql = "select r.id,r.name,re.name as pname,re.id as pid,r.url from resource as r left join user_resource as ur on r.id=ur.resourceid left join resource as re on  r.pid=re.id left join    where r.type=1 and ur.userid=%d"%(int(uid))
    # res = db.find_all(sql)
    sql = "select r.name,r.url,r.id,pr.id as pid,pr.name as pname from user_resource as ur left join resource as r on ur.resourceid=r.id left join resource as pr on pr.id=r.pid where ur.userid=%d and r.type=1 union select r.name,r.url,r.id,pr.id as pid,pr.name as pname from user_jue as ur left join jue_resource as rr on ur.jueid=rr.jueid left join resource as r on rr.resourceid=r.id left join resource as pr on pr.id=r.pid where ur.userid=%d and r.type=1"%(int(uid),int(uid))
    res = db.find_all(sql)

    lst = gettwocate(res)
    return jsonify({'code':200,'list':lst})


#穿梭表  获取管理员权限
@bp_user.route('/getadmin/')
async def getadmin():
    uid = 4
    #先查看管理员对用那个角色  角色对应那些资源 r.id,
    sql = "select r.id,r.name as rname from users as u left join user_jue as uj on u.id=uj.userid left join jue_resource as jr on uj.jueid=jr.jueid left join resource as r on jr.resourceid = r.id where u.id=%d"%(int(uid))

    res = db.find_all(sql)
    return jsonify({'code':200,'list':res})

#获取用户权限
@bp_user.route('/getuser/',methods=['POST','GET'])
async def getuser():
    if request.method == 'GET':
        sql = "select * from users"
        res = db.find_all(sql)
        return jsonify({'code':200,'list':res})
    else:
        userid = request.form.get('userid')
        values = eval(request.form.get('values'))
        print(values)
        #写入用户资源表   角色资源表是固定的
        for i in values: 
            print(i)
            sql = "insert into user_resource value(%d,%d)"%(int(userid),int(i))
            db.insert(sql)
        return jsonify({'code':200})




#获取角色资源  角色管理
@bp_user.route('/getjue/',methods=['POST','GET'])
async def getjue():
    if request.method == 'GET':
        #获取所有角色  [{'name':总经理,'resource':"[1,2,3,4]"}]
        sql = "select *  from jue inner join jue_resource as jr on jue.id=jr.jueid"
        res = db.find_all(sql)
        # print(res)
        lst = []
        lst1=[]
        for i in res:
            if i['id'] not in lst1:
                lst1.append(i['id'])
                lst.append({'id':i['id'],'name':i['name'],'resource':[]})
        for j,k in enumerate(lst):
            for i in res:
                if k['id'] ==i['id']:
                    lst[j]['resource'].append(i['resourceid'])


            
        return jsonify({'code':200,'list':lst})
    #角色继承
    elif request.method =='POST':
        
        # jueid = request.form.get('jueid')
        # value = eval(request.form.get('value'))
        # resource = eval(request.form.get('resource'))
        
        # for i in value:
        #     if i not in resource:
        #         resource.append(i)
        # # print(resource)
        # #删除原来角色资源表的数据
        # sql = "delete from  jue_resource  where jueid = %d"%(int(jueid))
        # db.delete(sql)
        # for k in resource:
        #     # print(k,type(k))
        #     sql1  = "insert  into  jue_resource value(%d,%d)"%(int(jueid),int(k))
        #     db.insert(sql1)
        
        return jsonify({"code":200})






#abac 属性判断
@bp_user.route('/abacif/')
async def abacif():
    opt = request.method
    print(opt)
    #显示方法是读取才可以执行
    if opt == 'GET':
        key = 'abac'
        r.hset_set(key, 'ip', '127.0.0.1')
        r.hset_set(key, 'level', '003')
        r.hset_set(key, 'time', "['2021-10-1','2021-11-01']")
        values = r.hget_gets(key)
        # print(values)
        for (k,v) in values.items():
            print(k)
            #判断属性是否是时间 
            if str(k,encoding='utf8') == 'time':
                print(eval(v))

    return 'ok'











